package org.windowkit.toolkit.widget.treetable;

import java.util.ArrayList;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreePath;

/**
 * This model handles event related operations for a {@link TreeTableModel}
 *
 * @author Eric Lundin
 */
public abstract class AbstractTreeTableModel implements TreeTableModel {

	private final ArrayList<TreeModelListener> listenerList;

	public AbstractTreeTableModel() {
		listenerList = new ArrayList<TreeModelListener>();
	}

	public void addTreeModelListener(final TreeModelListener l) {
		listenerList.add(l);
	}

	public void removeTreeModelListener(final TreeModelListener l) {
		listenerList.remove(l);
	}

	protected void fireTreeNodesChanged(final Object source, final Object[] path,
			final int[] childIndices, final Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (int i = 0; i < listenerList.size(); i++) {
			listenerList.get(i).treeNodesChanged(e);
		}
	}

	protected void fireTreeNodesInserted(final Object source, final Object[] path,
			final int[] childIndices, final Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (int i = 0; i < listenerList.size(); i++) {
			listenerList.get(i).treeNodesInserted(e);
		}
	}

	protected void fireTreeNodesRemoved(final Object source, final Object[] path,
			final int[] childIndices, final Object[] children) {
		TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
				children);
		for (int i = 0; i < listenerList.size(); i++) {
			listenerList.get(i).treeNodesRemoved(e);
		}
	}

	// protected void fireTreeStructureChanged(Object source, Object[] path,
	// int[] childIndices, Object[] children) {
	// TreeModelEvent e = new TreeModelEvent(source, path, childIndices,
	// children);
	// for (int i = 0; i < listenerList.size(); i++) {
	// listenerList.get(i).treeStructureChanged(e);
	// }
	// }

	protected void fireTreeStructureChanged(final Object source, final TreePath path) {
		TreeModelEvent e = null;
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = 0; i < listenerList.size(); i++) {
			if (e == null) {
				e = new TreeModelEvent(source, path);
			}
			listenerList.get(i).treeStructureChanged(e);
		}
	}

}
